package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;


@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Autowired
    private VodProperties vodProperties;
    // 上传声音
    @Override
    public Map<String, Object> uploadTrack(MultipartFile file) {
        //0.定义局部变量
        String mediaUrl = "";
        String fileId = "";

        // 1、初始化一个上传客户端
        VodUploadClient client = new VodUploadClient(vodProperties.getSecretId(), vodProperties.getSecretKey());
        // 2.构建上传请求对象
        VodUploadRequest request = new VodUploadRequest();
        // 2.1要上传文件的地址(上传临时文件路径并设置请求的媒体文件路径)
        String tempPath = UploadFileUtil.uploadTempPath(vodProperties.getTempPath(), file);
        request.setMediaFilePath(tempPath);
        //对大文件起作用。（s3：minio:大文件上传（断点续传 秒传  分片上传 ））
        request.setConcurrentUploadNumber(5);
        // 3.调用上传方法
        try {
            VodUploadResponse response = client.upload(vodProperties.getRegion(), request);
            mediaUrl = response.getMediaUrl();
            fileId = response.getFileId();
            log.info("Upload FileId = {}", response.getFileId());
            // 上传成功后删除临时文件中文件
            deleteDirectory(tempPath);
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
        }
        // 4.构建上传视频在vod的文件标识以及地址
        HashMap<String, Object> map = new HashMap<>();
        map.put("mediaFileId", fileId);
        map.put("mediaUrl", mediaUrl);
        return map;
    }

    // 删除临时文件
    private void deleteDirectory(String dirPath) {
        Path directory = Paths.get(dirPath);
        try (Stream<Path> stream = Files.walk(directory);) {
            // 逆序遍历以先删除子文件和子目录
            stream.sorted((p1, p2) -> -p1.compareTo(p2))
                    .map(Path::toFile).forEach(File::delete);
            log.info("目录及其内容已删除: {}", dirPath);
        } catch (IOException e) {
            log.error("删除目录失败: {}", dirPath, e);
        }
    }
    // 获取媒体详细信息
    @Override
    public TrackMediaInfoVo getMediaInfo(String mediaFileId)  {
        try {
            Credential credential = new Credential(vodProperties.getSecretId(), vodProperties.getSecretKey());
            VodClient vodClient = new VodClient(credential, vodProperties.getRegion());
            DescribeMediaInfosRequest request = new DescribeMediaInfosRequest();
            String[] fileIds1 = {mediaFileId};
            request.setFileIds(fileIds1);
            DescribeMediaInfosResponse resp = vodClient.DescribeMediaInfos(request);
            // 输出json格式的字符串回包
            System.out.println(AbstractModel.toJsonString(resp));
            TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
            MediaInfo[] mediaInfoSet = resp.getMediaInfoSet();
            if (mediaInfoSet != null && mediaInfoSet.length > 0) {
                MediaInfo mediaInfo = mediaInfoSet[0];
                MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                MediaMetaData metaData = mediaInfo.getMetaData();
                Float audioDuration = metaData.getAudioDuration();
                trackMediaInfoVo.setSize(metaData.getSize());
                trackMediaInfoVo.setDuration(audioDuration);
                trackMediaInfoVo.setMediaUrl(basicInfo.getMediaUrl());
                trackMediaInfoVo.setType(basicInfo.getType());
            }
            return trackMediaInfoVo;
        } catch (TencentCloudSDKException e) {
            // 异常吃掉了
            log.error("获取媒体信息失败：{}", e.getMessage());
            return null;
        }
    }
    //删除Vod文件
    @Override
    public void removeVodMedia(String mediaFileId) {
        try {
            Credential cred = new Credential(vodProperties.getSecretId(), vodProperties.getSecretKey());
            // 实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodProperties.getRegion());
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            // 返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            DeleteMediaResponse resp = client.DeleteMedia(req);
            // 输出json格式的字符串回包
            System.out.println(AbstractModel.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error("删除vod中的媒体资源失败:{}",e.getMessage());
            throw new GuiguException(201,"删除vod中的媒体资源失败");
        }
    }
}